﻿using Dapr.Actors.Runtime;
using FEShop.AppUserService.Models;
using FEShop.AppUserService.Services.Dtos.Account;
using FEShop.AppUserService.Services.Interfaces;
using FEShop.OpenModel.Common;
using System.Linq;

namespace FEShop.AppUserService.Services.Implementations
{
    /// <summary>
    /// 
    /// </summary>
    public class AccountService : Actor, IAccountService
    {
        private readonly ILogger<UserService> _logger;
        private readonly AppUserDbContext DbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="logger"></param>
        public AccountService(ActorHost host, ILogger<UserService> logger, AppUserDbContext dbContext) : base(host)
        {
            _logger = logger;
            DbContext = dbContext;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultObject<LoginOutputDto>> LoginAsync(LoginInputDto dto)
        {
            //查询用户信息
            _logger.LogWarning("用户登录：");
            _logger.LogDebug(_logger.IsEnabled(LogLevel.Debug) ? "账号：{Account}, 密码：{Password}" : "账号：{Account}", dto.Account, dto.Password);
            var db = DbContext.GetInstance();
            var user = db.Queryable<AppUser>()
                .Where(it => it.Account == dto.Account && it.Password == dto.Password)
                .First();
            if (user == null)
            {
                return new ResultObject<LoginOutputDto>
                {
                    Result = false,
                    Message = "账号或密码错误",
                };
            }

            //生成Token
            _logger.LogWarning("====================登录成功=========================");
            await Task.CompletedTask;

            return new ResultObject<LoginOutputDto>
            {
                Code = 200,
                Message = "登录成功",
                Result = true,
                Data = new LoginOutputDto
                {
                    Account = dto.Account,
                    Token = "token_" + dto.Account,
                    RefreshToken = "refresh_token_" + dto.Account,
                }
            };

        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ResultObject<string>> RegisterAsync(RegisterInputDto dto)
        {
            throw new NotImplementedException();
        }
    }
}
